<?php


namespace app\api;


use think\Controller;

class BaseApi extends Controller
{
    protected function initialize()
    {
        parent::initialize();

        // 初始化代码
        //允许的源域名
        header("Access-Control-Allow-Origin: *");
        //允许的请求头信息
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        //允许的请求类型
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
    }

    /**
     * 通用响应
     * @param int $code
     * @param string $msg
     * @param array $data
     */
    protected function response($code = 200, $msg = 'success', $data = [])
    {
        $res = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        json($res)->send();
        die;
    }

    /**
     * 成功返回的方法
     * @param array $data
     * @param int $code
     * @param string $msg
     */
    protected function outPutSucc($data = [], $code = 200, $msg = "success")
    {
        return $this->response($code, $msg, $data);
    }

    /**
     * 错误的返回方法
     * @param string $message
     * @param int $code
     * @param array $data
     */
    protected function outPutFail($message = 'fail', $code = 500, $data = [])
    {
        return $this->response($code, $message, $data);
    }
}